package com.business.business.web.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.business.business.common.base.BaseService;
import com.business.business.model.BusinessBasisinfoImg;
import com.business.business.model.BusinessFirefightingplan;
import com.business.business.model.fireplan.FireFlanStorey;
import com.business.business.model.fireplan.FirePlanCoordinate;
import com.business.business.model.fireplan.FirePlanFloor;
import com.business.business.support.model.RespEntity;
import com.business.business.support.mybatisplus.QueryWrapper;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.BusinessBasisinfoImgMapper;
import com.business.business.web.mapper.BusinessFirefightingplanMapper;
import com.business.business.web.mapper.BusinessMapper;
import com.business.business.web.mapper.fireplan.FireFlanStoreyMapper;
import com.business.business.web.mapper.fireplan.FirePlanCoordinateMapper;
import com.business.business.web.mapper.fireplan.FirePlanFloorMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: YangYu
 * @ClassName: FirefightingplanService
 * @Date: Created in 10:14 2021/1/21
 * @Description: 消防平面图
 */
@Service
@Slf4j
public class FirefightingplanService extends BaseService {
    private static final Logger logger = LoggerFactory.getLogger(FirefightingplanService.class);
    @Resource
    private BusinessBasisinfoImgMapper businessBasisinfoImgMapper;
    @Resource
    private BusinessFirefightingplanMapper businessFirefightingplanMapper;
    @Resource
    private FirePlanFloorMapper firePlanFloorMapper;
    @Resource
    private FireFlanStoreyMapper fireFlanStoreyMapper;
    @Resource
    private FirePlanCoordinateMapper firePlanCoordinateMapper;
    @Resource
    private BusinessMapper businessMapper;

    /**
     * @Author YangYu
     * @Description 楼层分页列表
     * @Date Created in 10:05 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity storeyListPage(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        Page<FireFlanStorey> page = new Page<>(jsonParam.getInt("page"),jsonParam.getInt("limit"));
        IPage<FireFlanStorey> iPage =  fireFlanStoreyMapper.storeyListPage(page, jsonParam);
        List<FireFlanStorey> records = iPage.getRecords();
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", iPage.getTotal());
        data.put("pages", iPage.getPages());
        data.put("pageSize", jsonParam.getInt("limit"));
        data.put("Items",records);
        data.put("currentPage",jsonParam.getInt("page"));
        data.put("currentSize",jsonParam.getInt("limit"));
        return RespEntity.success(data);
    }
    /**
     * @Author YangYu
     * @Description 楼层新增、编辑
     * @Date Created in 9:33 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity storeyAddOrUpdate(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (!jsonParam.containsKey("id")){
            jsonParam.put("id",UUID.randomUUID().toString());
        }else {
            //删除原数据
            fireFlanStoreyMapper.deleteById(jsonParam.getStr("id"));
            firePlanCoordinateMapper.delete(new QueryWrapper<FirePlanCoordinate>().eq("storey_id",jsonParam.getStr("id")));
        }
        if (jsonParam.getJSONArray("coordinateData").size() <= 0){
            return RespEntity.fail("坐标数据不能为空");
        }
        save(jsonParam);
        updateSave(jsonParam);
        return RespEntity.success();
    }

    private void save(JSONObject jsonParam){
        FireFlanStorey fireFlanStorey = new FireFlanStorey();
        fireFlanStorey.setId(jsonParam.getStr("id"));
        fireFlanStorey.setFloorId(jsonParam.getStr("floorId"));
        fireFlanStorey.setName(jsonParam.getStr("name"));
        fireFlanStorey.setPath(jsonParam.getStr("path"));
        fireFlanStoreyMapper.insert(fireFlanStorey);
        JSONArray jsonArray = jsonParam.getJSONArray("coordinateData");
        List<FirePlanCoordinate> list = com.alibaba.fastjson.JSONObject.parseArray(jsonArray.toJSONString(0),FirePlanCoordinate.class);
        for (FirePlanCoordinate firePlanCoordinate : list){
            firePlanCoordinate.setStoreyId(jsonParam.getStr("id"));
        }
        fireFlanStoreyMapper.insertZB(list);
    }
    private void updateSave(JSONObject jsonParam){
        JSONArray coordinateData = jsonParam.getJSONArray("coordinateData");
        List<String> ids = new ArrayList<>();
        for (Object obj : coordinateData){
            JSONObject jsonObject = (JSONObject) obj;
            ids.add(jsonObject.getStr("deviceId"));
        }
        fireFlanStoreyMapper.batchUpdate(ids,jsonParam.getStr("id"));
    }
    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceId","111");
        jsonObject.put("storeyId","111");
        jsonObject.put("x","111");
        jsonObject.put("y","111");
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("deviceId","2");
        jsonObject.put("storeyId","2");
        jsonObject.put("x","2");
        jsonObject.put("y","2");
        jsonArray.add(jsonObject);
        List<FirePlanCoordinate> list = com.alibaba.fastjson.JSONObject.parseArray(jsonArray.toJSONString(0),FirePlanCoordinate.class);
        System.out.println(jsonArray);
        System.out.println(list);
    }

    /**
     * @Author YangYu
     * @Description 楼层详情
     * @Date Created in 14:39 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity storeyDetails(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("ID不能为空");
        }
        FireFlanStorey fireFlanStorey = fireFlanStoreyMapper.selectById(jsonParam.getStr("id"));
        if (fireFlanStorey == null){
            return RespEntity.success();
        }
        List<FirePlanCoordinate> firePlanCoordinates = firePlanCoordinateMapper.selectList(new QueryWrapper<FirePlanCoordinate>().eq("storey_id",jsonParam.getStr("id")));
        fireFlanStorey.put("coordinateData",firePlanCoordinates);
        return RespEntity.success(fireFlanStorey);
    }
    /**
     * @Author YangYu
     * @Description 楼层删除
     * @Date Created in 9:33 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity storeyDel(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("ID不能为空");
        }
        //删除
        fireFlanStoreyMapper.deleteById(jsonParam.getStr("id"));
        firePlanCoordinateMapper.delete(new QueryWrapper<FirePlanCoordinate>().eq("storey_id",jsonParam.getStr("id")));
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 楼栋分页列表
     * @Date Created in 10:05 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity floorListPage(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        Page<FirePlanFloor> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        if (!jsonParam.containsKey("businessId") || StrUtil.isBlank(jsonParam.getStr("businessId"))){
            jsonParam.put("businessId",homeId);
        }
        IPage<FirePlanFloor> pageList = firePlanFloorMapper.floorListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * @Author YangYu
     * @Description 楼栋新增、编辑
     * @Date Created in 9:33 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity floorAddOrUpdate(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        FirePlanFloor firePlanFloor = new FirePlanFloor();
        if (jsonParam.containsKey("businessId") || StrUtil.isNotBlank(jsonParam.getStr("businessId"))){
            homeId = jsonParam.getStr("businessId");
        }
        firePlanFloor.setBusinessId(homeId);
        if (!jsonParam.containsKey("id")){
            firePlanFloor.setId(UUID.randomUUID().toString());
            firePlanFloor.setName(jsonParam.getStr("name"));
            firePlanFloorMapper.insert(firePlanFloor);
        }else {
            firePlanFloor.setId(jsonParam.getStr("id"));
            firePlanFloor.setName(jsonParam.getStr("name"));
            firePlanFloorMapper.updateById(firePlanFloor);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 楼栋删除
     * @Date Created in 9:33 2022/7/25
     * @Param [jsonParam]
     */

    public RespEntity floorDel(JSONObject jsonParam){
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("ID不能为空");
        }
        int count  = fireFlanStoreyMapper.selectCount(new QueryWrapper<FireFlanStorey>().eq("floor_id",jsonParam.getStr("id")));
        if (count >0){
            return RespEntity.fail("请先删除楼层数据!");
        }
        firePlanFloorMapper.deleteById(jsonParam.getStr("id"));
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description //TODO
     * @Date Created in 9:46 2022/7/25
     * @Param [id, jsonParam]
     */

    public RespEntity firefightingplanById(String id, JSONObject jsonParam) {
        System.out.println(id);
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        //调用token验证接口
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String home_id = token.getString("home_id");
        System.out.println(home_id);
        BusinessBasisinfoImg businessBasisinfoImg = businessBasisinfoImgMapper.selectById(id);
        String path = businessBasisinfoImg.getPath();
        return RespEntity.success(path);
    }
    
    /**
     * @Author LiHaoDong
     * @Description 消防平面图列表
     * @Date 16:36 2020/7/22
     * @Param [jsonParam]
     * @return com.business.business.support.model.RespEntity
     **/
    public RespEntity firefightingplanListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());

        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        //调用token验证接口
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if ("2".equals(userType)){
            jsonParam.put("businessId",homeId);
        }
        Page<BusinessFirefightingplan> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<BusinessFirefightingplan> iPage = this.businessFirefightingplanMapper.firefightingplanListPage(page, jsonParam);
        List<BusinessFirefightingplan> records = iPage.getRecords();

        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", iPage.getTotal());
        data.put("pages", iPage.getPages());
        data.put("pageSize", jsonParam.getInt("limit"));
        data.put("Items",records);
        data.put("currentPage",jsonParam.getInt("page"));
        data.put("currentSize",jsonParam.getInt("limit"));
        return RespEntity.success(data);
    }

    /**
     * @Author LiHaoDong
     * @Description 消防平面图详情详情
     * @Date 16:57 2020/7/22
     * @Param [jsonParam]
     * @return com.business.business.support.model.RespEntity
     **/
    public RespEntity firefightingplanDetail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());

        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        //调用token验证接口
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String id = jsonParam.getStr("id");
        BusinessFirefightingplan businessFirefightingplan = this.businessFirefightingplanMapper.firefightingplanDetail(id);
        List<BusinessBasisinfoImg> basisinfoImgList = businessBasisinfoImgMapper.selectList(new QueryWrapper<BusinessBasisinfoImg>().eq("business_basisinfo_id",id));
        BusinessBasisinfoImg businessBasisinfoImg = basisinfoImgList.get(0);
        if (!businessFirefightingplan.isEmpty()) {
            businessFirefightingplan.put("path",businessBasisinfoImg);
            return RespEntity.success(businessFirefightingplan);
        }
        return RespEntity.fail("查询失败");
    }

    /**
     * @Author LiHaoDong
     * @Description 消防平面图新增
     * @Date 17:16 2020/7/22
     * @Param [jsonParam]
     * @return com.business.business.support.model.RespEntity
     **/
    public RespEntity firefightingplanAdd(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());

        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        //调用token验证接口
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if ("1".equals(userType)){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }
        String type = jsonParam.getStr("type");
        String name = jsonParam.getStr("name");
        String fileName = jsonParam.getStr("fileName");
        String filePath = jsonParam.getStr("filePath");

        String id = UUID.randomUUID().toString();
        DateTime date = DateUtil.date();
        String year = DateUtil.year(date)+"";

        BusinessFirefightingplan businessFirefightingplan = new BusinessFirefightingplan();
        businessFirefightingplan.setId(id);
        businessFirefightingplan.setType(type);
        businessFirefightingplan.setName(name);
        businessFirefightingplan.setBusinessId(businessId);
        businessFirefightingplan.setCreatetime(date);
        businessFirefightingplan.setCreateyear(year);
        //保存在消防平面图
        int insertFirefightingplan = this.businessFirefightingplanMapper.insert(businessFirefightingplan);
        BusinessBasisinfoImg businessBasisinfoImg = new BusinessBasisinfoImg();
        businessBasisinfoImg.setBusinessBasisinfoId(id);
        businessBasisinfoImg.setName(fileName);
        businessBasisinfoImg.setPath(filePath);
        int insertBasisinfoImg = this.businessBasisinfoImgMapper.insert(businessBasisinfoImg);
        if (insertBasisinfoImg > 0 && insertFirefightingplan > 0) {
            return RespEntity.success();
        }
        return RespEntity.fail("插入失败");
    }

    /**
     * @Author LiHaoDong
     * @Description 消防平面图修改
     * @Date 17:32 2020/7/22
     * @Param [jsonParam]
     * @return com.business.business.support.model.RespEntity
     **/
    public RespEntity firefightingplanUpdate(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());

        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        //调用token验证接口
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");

        String type = jsonParam.getStr("type");
        String name = jsonParam.getStr("name");
        String fileName = jsonParam.getStr("fileName");
        String id = jsonParam.getStr("id");
        String filePath = jsonParam.getStr("filePath");
        //删除business_basisinfo_img
        QueryWrapper queryWrapper = new QueryWrapper<BusinessBasisinfoImg>();
        queryWrapper.eq("business_basisinfo_id", id);
        int delete = this.businessBasisinfoImgMapper.delete(queryWrapper);
        //插入business_basisinfo_img
        BusinessBasisinfoImg businessBasisinfoImg = new BusinessBasisinfoImg();
        businessBasisinfoImg.setBusinessBasisinfoId(id);
        businessBasisinfoImg.setName(fileName);
        businessBasisinfoImg.setPath(filePath);
        int insert = this.businessBasisinfoImgMapper.insert(businessBasisinfoImg);
        //更新主表
        BusinessFirefightingplan businessFirefightingplan = new BusinessFirefightingplan();
        businessFirefightingplan.setId(id);
        businessFirefightingplan.setType(type);
        businessFirefightingplan.setName(name);
        int update = this.businessFirefightingplanMapper.updateById(businessFirefightingplan);
        if (delete > 0 && insert > 0 && update > 0) {
            return RespEntity.success();
        }
        return RespEntity.fail("修改失败");
    }

    /**
     * @Author LiHaoDong
     * @Description 消防平面图删除
     * @Date 17:48 2020/7/22
     * @Param [jsonParam]
     * @return com.business.business.support.model.RespEntity
     **/
    public RespEntity firefightingplanDelete(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());

        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam,"systemsetup","config","getDecodeToken","systemsetup");
        //调用token验证接口
        if(StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if(StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");

        String id = jsonParam.getStr("id");
        //删除business_basisinfo_img
        QueryWrapper queryWrapper = new QueryWrapper<BusinessBasisinfoImg>();
        queryWrapper.eq("business_basisinfo_id", id);
        int deleteBasisinfoImg = this.businessBasisinfoImgMapper.delete(queryWrapper);

        int deleteFirefightingplan = this.businessFirefightingplanMapper.deleteById(id);

        if (deleteBasisinfoImg > 0 && deleteFirefightingplan > 0) {
            return RespEntity.success();
        }
        return RespEntity.fail("删除失败");
    }
}
